/**
 * OverView: APK原生接口类
 * Author: Zhaomi
 * Date: 13-5-14 下午12:29
 * Email: yanyuetian@gmail.com
 * Create By JetBrains WebStorm.
 */
console.log("--- bridge starts initialization ---");

var global = window;
var NineGameClient = {};
var ua = navigator.userAgent;

/**
 * 下面的属性用来判断 当前 页面运行环境，false为PC浏览器，true为移动设备
 * */
var isMobileModel = global.IS_MOBILE_MODE = ua.indexOf("Android") != -1;

var JSBridge = {
    callbackCache: [],
    callbackId: 0,
    getCallbackId: function () {
        return JSBridge.callbackId++;
    },
    callNative: function(clz, method, args, callback) {
        var p = {};
        p.clz = clz;
        p.method = method;
        if (args != undefined)
            p.args = args;

        if (callback) {
            var callbackId = JSBridge.getCallbackId();
            JSBridge.callbackCache[callbackId] = callback;
            if (p.args) {
                p.args.callbackId = callbackId.toString();
            } else {
                p.args = { "callbackId": callbackId.toString() };
            }
        }
        if(isMobileModel)
            return prompt(JSON.stringify(p));
        else
            return null;
    },
    onCallback: function (callbackId, obj) {
        if (JSBridge.callbackCache[callbackId]) {
            JSBridge.callbackCache[callbackId](obj);
            JSBridge.callbackCache[callbackId] = undefined;
        }
    }
};

global.JSBridge = JSBridge;
/**
 * 先定义壳需要通过NineGameClient回调的函数
 * */
NineGameClient.onSetImage = function (srcSuffix) {
    var obj = document.querySelectorAll('img[src$="'+ srcSuffix +'"]');
    for (var i = 0; i < obj.length; ++i) {
        obj[i].src = obj[i].src;
    }
};

// callback = function(pkgName, state)
exports.registerDownloadStateChangeListener = function (callback) {
    NineGameClient.onDownloadStateChange = callback;
};
/*滚动到页面底部时的回调函数 以及 设置的阀值*/
exports.registerHitPageBottomListener = function (callback,threshold) {
    JSBridge.callNative("NineGameClient", "setHitPageBottomThreshold", {"threshold": threshold});
    NineGameClient.onHitPageBottom = callback;
};

/*系列间的横向Tab切换时的回调函数注册*/
exports.registerHorizonTabSwitchListener = function (callback) {
    NineGameClient.onHorizonTabSwitch = callback;
};

/**评论回调函数的定义**/
exports.setAddCommentFunc = function(callback){
    NineGameClient.addCommentToPage =  callback;
};

/*回调函数callback返回JSON对象*/
exports.registerSettingChangeListener = function(callback) {
    NineGameClient.onSettingsChanged = callback;
};

/**
 * 页面预加载完成后的壳的框架布局完成时,
 * 如果该函数在脚本某处定义了，就触发调用
 * */
NineGameClient.onLayoutInitSuccess = null;

global.NineGameClient = NineGameClient;

/**
 * 下面定义需要壳同步获取相关信息 或 功能接口函数
 * */
exports.startupNativeApp = function (pkgName) {
    JSBridge.callNative("NineGameClient", "startupApp", {"pkgName": pkgName});
};

exports.getCurDownloadingTasksAsync = function (callback) {
    JSBridge.callNative("NineGameClient", "getCurDownloadingTasksAsync", undefined, callback);
};

// callback = function(); which is called when this function did successfully start a new download task
// this callback will not be invoked when network connection is unavailable
exports.downloadApp = function (gameId, pkgName, appName, versionName, versionCode, appUrl, appIconUrl, size, sig, gameType, category, callback) {
    JSBridge.callNative("NineGameClient", "downloadApp"
        , {"gameId": gameId, "pkgName": pkgName, "appName": appName, "versionName": versionName, "versionCode": versionCode
            , "appUrl": appUrl, "appIconUrl": appIconUrl, "size": size, "sig": sig, "gameType": gameType, "category": category}, callback);
};

exports.downloadApp2 = function (jsonObject, callback) {
    // I test in the native code the existence of the "jsonObj" property to know whether it is
    // "downloadApp" or "downloadApp2", so I don't need a corresponding `downloadApp2` in the native code
    JSBridge.callNative("NineGameClient", "downloadApp", {"jsonObj": jsonObject}, callback);
};

exports.installApp = function (gameId, pkgName) {
    JSBridge.callNative("NineGameClient", "installApp", {"gameId": gameId, "pkgName": pkgName});
};

// 返回0表示本地不存在此应用(显示“安装”，启动下载，或者把下载任务添加到pending队列)
// 返回1表示已安装的包版本>=门户上的包的版本(显示“打开”，点击启动应用)
// 返回2表示已安装的包版本<门户上的包的版本(显示“升级”，启动下载，或者把下载任务添加到pending队列)
// 返回3表示正在下载(开始显示“暂停”)
// 返回4表示下载任务被暂停(显示“继续”，启动下载，或者把下载任务添加到pending队列)
// 返回5表示本地不存在此应用，但已下载完成(显示“安装”，启动安装程序)
// 返回6表示已安装的包版本<门户上的包的版本，并且已成功下载最新版本(显示“升级”，启动安装程序)
exports.getPackageState = function (gameId, pkgName, versionCode, callback) {
    JSBridge.callNative("NineGameClient", "getPackageState", {"gameId": gameId, "pkgName": pkgName, "versionCode": versionCode}, callback)
};

exports.stopDownloadTask = function(gameId, pkgName) {
    JSBridge.callNative("NineGameClient", "stopDownloadTask", {"gameId": gameId, "pkgName": pkgName});
};

exports.resumeDownloadTask = function(gameId, pkgName, callback) {
    JSBridge.callNative("NineGameClient", "resumeDownloadTask", {"gameId": gameId, "pkgName": pkgName}, callback);
};

exports.setEnableTouchScrollForWebView = function(flag) {
    JSBridge.callNative("NineGameClient", "setEnableTouchScrollForWebView", {"flag": flag});
};

exports.setGameDetailPageScroll = function(isDisable) {
    JSBridge.callNative("NineGameClient", "setGameDetailPageScroll", {"isDisable": isDisable});
};

exports.getImgCacheDir = function () {
    return JSBridge.callNative("NineGameClient", "getImgCacheDir", {});
};

exports.showMessage = function (msg) {
    JSBridge.callNative("NineGameClient", "showMessage", {"msg": msg});
};
exports.showSearchDialog = function () {
    JSBridge.callNative("NineGameClient", "showSearchDialog");
};

/**举报接口**/
exports.showReportDialog = function (reportArgs) {
    JSBridge.callNative("NineGameClient", "showReportDialog",{"jsonObj": reportArgs});
};

/**设置专区页的"玩家评论" 标题的 数字**/
exports.setCommentNumInTab = function(mcount) {
    JSBridge.callNative("NineGameClient", "setCommentNumInTab",{"count": mcount});
};

/**同步获取文件内容**/
exports.readFileSync = function(path, encoding){
    return JSBridge.callNative("NineGameClient", "readFileSync", {"path": path, "encoding": encoding});
};

/**异步获取文件内容**/
exports.readFileAsync = function(path, encoding, callback){
    JSBridge.callNative("NineGameClient", "readFileAsync", {"path": path, "encoding": encoding},callback);
};

exports.setSessionString = function (key, value) {
    JSBridge.callNative("NineGameClient", "setSessionString", {"key": key, "value": value});
};

exports.getSessionString = function (key, clearCache, callback) {
    if (callback)
        JSBridge.callNative("NineGameClient", "getSessionString", {"key": key, "clearCache": clearCache}, callback);
    else
        return JSBridge.callNative("NineGameClient", "getSessionString", {"key": key, "clearCache": clearCache});
};

exports.setCurrentDownloadInfo = function (jsonStr) {
    JSBridge.callNative("NineGameClient", "setCurrentDownloadInfo", {"info": jsonStr});
};

exports.goBack = function() {
    JSBridge.callNative("NineGameClient", "goBackInCurrentWebView");
};

exports.setTopNavTitle = function (title) {
    JSBridge.callNative("NineGameClient", "setTopNavTitle", {"title": title});
};

exports.addStat = function(key) {
    //exports.showMessage(key);
    JSBridge.callNative("NineGameClient", "addStat", {"key": key});
};

// ["path1", "path2", "path3"]
exports.showSlideShow = function(json, allScreen, tapIdx) {
    JSBridge.callNative("NineGameClient", "showSlideShow", {"json": json,"isAllScreen":allScreen, "selectedIndex": tapIdx});
};

exports.getScreenDimension = function() {
    return JSBridge.callNative("NineGameClient", "getScreenDimension");
};

exports.isLoadingImagesEnabled = function(){ /*返回1有图，返回0无图*/
    return JSBridge.callNative("NineGameClient", "isLoadingImagesEnabled") == "true";
};

/*get函数返回string对象*/
exports.getSettingProperties = function(){
    return JSBridge.callNative("NineGameClient", "getSettingProperties");
};

exports.setLotteryState = function(state, url) {
    JSBridge.callNative("NineGameClient", "setLotteryState", {"state": state,"url": url});
};

/*
 *依据属性名获取环境信息值
 * */
exports.getEnvAttr = function(attrName){
    return JSBridge.callNative("NineGameClient", "getAttributeValue", {"flag": attrName});
};

//v1.2.3 native supported
//flag, switch closet, true or false
exports.switchConsoleLog = function (flag) {
    JSBridge.callNative("NineGameClient", "switchWebViewConsoleLog", {"flag": flag});
};


var crossHttpRequest = function(){
    this.id = crossHttpRequest.globalId++;
};
crossHttpRequest.globalId = 1;
crossHttpRequest.cache = [];
crossHttpRequest.setProperties = function(jsonObj) {
    var id = jsonObj.id;
    if (crossHttpRequest.cache[id]) {
        var obj = crossHttpRequest.cache[id];

        if (jsonObj.hasOwnProperty('status')) {
            obj.status = jsonObj.status;
        }
        if (jsonObj.hasOwnProperty('statusText')) {
            obj.statusText = jsonObj.statusText;
        }
        if (jsonObj.hasOwnProperty('readyState')) {
            obj.readyState = jsonObj.readyState;
        }
        if (jsonObj.hasOwnProperty('responseText')) {
            obj.responseText = jsonObj.responseText;
        }
        if (jsonObj.hasOwnProperty('headers')) {
            obj.headers = jsonObj.headers;
        }

        if (obj.onreadystatechange) {
            obj.onreadystatechange();
        }
    }
};

crossHttpRequest.prototype.open = function(method, url, async) {
    /**
     * Zepto插件 在ajax时 是先 定义 onreadystatechange 再调用 open方法，故不能将 onreadystatechange置为空此处
     * */
    crossHttpRequest.cache[this.id] = this;
    this.status = 0;
    this.statusText = '';
    this.readyState = 0;
    this.responseText = '';
    this.headers = {};
    //this.onreadystatechange = undefined;
    JSBridge.callNative('XMLHttpRequest', 'open', {
        "id" : this.id,
        "method" : method,
        "url" : url,
        "referer" : document.referrer != "" ? document.referrer : null,
        "useragent" : navigator.userAgent,
        "cookie" : document.cookie != "" ? document.cookie : null
    });
};
/**
 * 忽略data内容
 * */
crossHttpRequest.prototype.send = function(data) {
    //exports.showMessage("CrossHttp send " + data + " | id " + this.id);
    //if (data) {
    //    JSBridge.callNative('XMLHttpRequest', 'send', { "id" : this.id, "data" : data });
    //} else {
    JSBridge.callNative('XMLHttpRequest', 'send', { "id" : this.id });
    //}
};
crossHttpRequest.prototype.overrideMimeType = function(mimetype) {
    JSBridge.callNative('XMLHttpRequest', 'overrideMimeType', { "id" : this.id, "mimetype" : mimetype });
};
crossHttpRequest.prototype.abort = function() {
    JSBridge.callNative('XMLHttpRequest', 'abort', { "id" : this.id });
};
crossHttpRequest.prototype.setRequestHeader = function(headerName, headerValue) {
    JSBridge.callNative('XMLHttpRequest', 'setRequestHeader', {
        "id" : this.id,
        "headerName" : headerName,
        "headerValue" : headerValue
    });
};
crossHttpRequest.prototype.getAllResponseHeaders = function() {
    var strHeaders = '';
    for ( var name in this.headers) {
        strHeaders += (name + ": " + this.headers[name] + "\r\n");
    }
    return strHeaders;
};
crossHttpRequest.prototype.getResponseHeader = function(headerName) {
    var strHeaders;
    var upperCaseHeaderName = headerName.toUpperCase();
    for ( var name in this.headers) {
        if (upperCaseHeaderName == name.toUpperCase())
            strHeaders = this.headers[name];
    }
    return strHeaders;
};
crossHttpRequest.deleteObject = function(id) {
    if (crossHttpRequest.cache[id]) {
        crossHttpRequest.cache[id] = undefined;
    }
};
/**
 * 重载之后的CrossHttpRequest对象不支持POST方法，即body里面不带data，切记！
 * */
exports.CrossHttpRequest= crossHttpRequest;
global.XMLHttpRequest.setProperties = crossHttpRequest.setProperties;

console.log("--- bridge finished initialization ---");

